<template>
  <!-- 审批通用页面组件 -->
  <div
    v-loading="loading"
    class="wrapper"
  >
    <div class="title">
      风险反馈
    </div>
    <title-name :title="processName + '-' + taskName" />
    <a-card
      :body-style="{ padding: '24px 32px' }"
      :bordered="false"
    >
      <template>
        <title-name title="节点信息" />
        <slot name="extraResult" />
        <a-descriptions
          class="mb20"
          title=""
        >
          <a-descriptions-item label="提示内容">
            {{ currentCommit.tipsContent }}
          </a-descriptions-item>
          <a-descriptions-item label="反馈人员">
            {{ currentCommit.tipsUserName }}
          </a-descriptions-item>
          <a-descriptions-item label="反馈时间">
            {{ currentTime }}
          </a-descriptions-item>
        </a-descriptions>
        <div
          v-if="assignType"
          class="mb20"
        >
          <title-name title="指派人员" />
          <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
            :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }"
          >
            <a-row :gutter="24">
              <a-col
                v-if="assignType == '3'"
                :md="12"
                :sm="12"
                class="col"
              >
                <a-form-model-item
                  label="组织"
                  prop="orgSelectedName"
                >
                  <TreeSelectOrganization
                    v-model="form.orgSelectedName"
                    :org-selected-value.sync="form.orgSelectedName"
                    :org-selected-label.sync="form.orgSelectedLabel"
                    :children-node="childrenNode"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="assignType == '3'"
                :md="12"
                :sm="12"
                class="col"
              >
                <a-form-model-item
                  label="岗位"
                  prop="jobsSelectedName"
                >
                  <Jobs
                    v-model="form.jobsSelectedName"
                    :selected-value.sync="form.jobsSelectedName"
                    :tree-checkable="treeCheckable"
                    :add-titel="form.orgSelectedLabel[0]"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                v-else
                :md="12"
                :sm="12"
                class="col"
              >
                <a-form-model-item
                  label="指派人员"
                  prop="respEmployeeId"
                >
                  <OrgStaffAsync
                    v-model="form.respEmployeeId"
                    :selected-value.sync="form.respEmployeeId"
                    :tree-checkable="assignType != '1'"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
      </template>

      <slot name="extraOption" />

      <template>
        <title-name title="附件" />
        <a-form
          ref="form1"
          :form="form"
        >
          <a-form-item class="approval-item">
            <b-upload
              business-code="LCM10"
              upload-type="single"
              :file-list.sync="form.fileInfoVO"
            />
          </a-form-item>
        </a-form>
        <title-name title="反馈意见" />
        <a-form
          ref="form1"
          :form="form"
        >
          <a-form-item class="approval-item">
            <BaseTextarea
              v-model="opinions"
              placeholder="请填写反馈意见"
            />
          </a-form-item>
          <slot name="extraMiddle" />
          <div class="overfloat">
            <div class="floatRight">
              <a-button
                v-if="!!detailUrl"
                type="success"
                style="margin-right: 20px"
                @click="handleDetail"
              >
                查看详情
              </a-button>
              <a-button
                v-if="buttonConfig.ok.isShow"
                type="primary"
                @click="handelApproval"
              >
                保存
              </a-button>
            </div>
          </div>
        </a-form>
      </template>
    </a-card>
  </div>
</template>

<script>
import { getProcessNodeList, completeTask } from '@/api/process'
import { getOrgEmployeesListBy } from '@/api/commons'
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import OrgStaffAsync from '@/components/TreeSelectOrganization/orgStaffAsync.vue'
import Jobs from '@/components/TreeSelectOrganization/jobs'
import moment from 'moment'
import Vue from 'vue'
import { notifyParentWindow } from '@/utils/util.js'
import riskListApi from '@/api/legal/risk/list'

const columnApprove = [
    {
        title: '序号',
        width: 80,
        scopedSlots: { customRender: 'serial' }
    },
    {
        title: '审批人',
        dataIndex: 'userName',
        ellipsis: true,
        width: 180
    },
    {
        title: '审批时间',
        dataIndex: 'createTime',
        ellipsis: true,
        width: 180
    },
    {
        title: '节点名称',
        dataIndex: 'taskName',
        ellipsis: true,
        width: 180
    },
    {
        title: '滞留时间',
        dataIndex: 'durationInMillis',
        ellipsis: true,
        width: 140
    },
    {
        title: '审批意见',
        dataIndex: 'formData.opinions',
        scopedSlots: { customRender: 'opinions' },
        ellipsis: true
    }
]

export default {
    name: 'Approval',
    components: {
        TreeSelectOrganization,
        Jobs,
        OrgStaffAsync
    },
    props: {
        text: String,
        /**
         * 审批时的回调，返回false时，会阻止审批；返回true时，则正常进行后续流程
         * @param {String} flag enum: 'approval' || 'unApproval'   通过 || 不通过
         */
        callbackFn: {
            type: [Function, Object],
            default: null
        },
        /*
        * 提交之后
        * */
        beforeSubmitFn: {
            type: [Function, Object],
            default: null
        },
        submitData: {
            type: Object,
            default() {
                return {}
            }
        },
        buttonConfig: {
            type: Object,
            default() {
                return {
                    no: {
                        isShow: true,
                        title: '审批不通过'
                    },
                    ok: {
                        isShow: true,
                        title: '审批通过'
                    }
                }
            }
        }
    },
    data() {
        return {
            form: {
                orgSelectedName: '',
                orgSelectedLabel: '',
                jobsSelectedName: undefined, //岗位
                respEmployeeId: undefined, //人员,
                fileInfoVO: []
            },
            treeCheckable: true,
            loading: false,

            childrenNode: 'jobs',

            columnApprove,
            opinions: '',
            approveInfos: [], // 审批流程信息
            procInstId: '', //当前流程实例ID
            taskId: '', //当前流程节点ID
            processName: '', //流程名称
            taskName: '', //当前流程节点名称
            taskDefKey: '', //任务标识
            currentTime: '', //当前审批时间
            currentUser: '', //当前审批人
            flowRequesting: false,
            detailUrl: null, //详情地址

            assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
            assignCode: '', //候选组编码 岗位编码
            assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
            businessType: '', //业务类型 0 项目,

            currentCommit: {}
        }
    },
    computed: {},
    created() {
        const {
            type,
            code,
            level,
            btype,
            businessId,
            procInstId,
            name,
            processName,
            detailUrl,
            taskId,
            taskDefKey
        } = this.$route.query
        if (type) {
            this.assignType = type
            this.assignCode = code
            this.assignLevel = level
            this.businessType = btype
        }
        this.id = businessId
        if (!this.id) {
            this.$error({ content: '无指定业务ID，将自动关闭' })
            setTimeout(() => {
                window.close()
            }, 1500)
            return
        }
        this.procInstId = procInstId
        this.taskName = decodeURIComponent(name)
        this.processName = decodeURIComponent(processName)
        document.title = this.processName + '-' + this.taskName
        if (detailUrl) {
            this.detailUrl = decodeURIComponent(detailUrl)
        }
        // else {
        //     this.detailUrl = '/process/auditBusinessDetail'
        // }
        this.taskId = taskId
        this.taskDefKey = taskDefKey
        this.currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
        this.currentUser = Vue.getAcloudProvider().getUserInfo()
        //获取流程节点执行情况
        this.getProcessNodes()
        this.getComments()
    },
    mounted() {

    },
    destroyed() {

    },
    methods: {
        async getComments() {
            let res = await riskListApi.findBaseByCommentsId({}, { id: this.id })
            if (res.code === this.SUCCESS_CODE) {
                let res1 = await riskListApi.findListByComments({}, { id: res.data.id })
                this.currentCommit = res1.data.find(v => v.id === this.id)
                console.log(this.currentCommit)
            }
        },
        handleDetail() {
            // const token = Vue.getAcloudProvider().getAccessToken();
            let routeData = this.$router.resolve({
                path: this.detailUrl,
                query: {
                    businessId: this.id,
                    businessType: this.$route.query.businessType || '',
                    id: this.id,
                    type: 'approve'
                }
            })
            window.open(routeData.href, '_blank')
        },
        getProcessNodes() {
            this.flowRequesting = true
            getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
                .then((res) => {
                    if (res.code === 200) {
                        const data = res.data
                        const userIds = data.map((d) => {
                            if (d.formData) {
                                d.formData = JSON.parse(d.formData)
                            }
                            return d.assignee
                        })
                        getOrgEmployeesListBy({ userIds }).then((employees) => {
                            this.flowRequesting = false
                            res.data.forEach((r) => {
                                employees.data.some((e) => {
                                    if (e.userId === r.assignee) {
                                        r.userName = e.name
                                        return true
                                    }
                                })
                            })
                            this.approveInfos = res.data
                        })
                    }
                })
                .catch(() => {
                    this.flowRequesting = false
                })
        },
        submit(reject) {
            const data = {
                formData: {
                    opinions: this.opinions,
                    reject,
                    projectId: ''
                },
                assignTypeEnum: this.assignType, //指派类型
                assgins: this.form.respEmployeeId, //人员
                groupEnum: this.form.jobsSelectedName, //岗位
                procInstId: this.procInstId,
                taskId: this.taskId,
                userId: this.currentUser.id
            }
            console.log(data)
            const variable = {}
            // return;
            if (reject) {
                variable.reject = true
            }

            data.variables = {
                ...variable,
                ...this.submitData // 特殊流程的数据，转交给审批
            }

            return completeTask(data)
                .then((res) => {
                    if (res.status === 200) {
                        notifyParentWindow() // 通知父窗口
                        // this.$success({
                        //     content: '保存成功，即将自动关闭当前窗口',
                        //     onOk() {
                                window.close()
                        //     }
                        // })
                        // setTimeout(() => {
                        //     window.close()
                        // }, 2000)
                    } else {
                        this.$error({ content: '保存失败，请稍后重试' })
                    }
                    return res
                })
                .catch((err) => {
                    return err
                })
        },
        async handelUnApproval() {
            const callbackFn = this.callbackFn
            if (callbackFn && !callbackFn('unApproval')) return

            if (!this.opinions) {
                this.$warning({ content: '请填写反馈意见' })
                return
            }
            const confirmWin = this.$confirm({
                title: '警告提醒！',
                content: '确定审批不通过？',
                okType: 'danger',
                onOk: async () => {

                    return new Promise((resolve, reject) => {
                        this
                            .submit(true)
                            .then(() => {
                                resolve()
                                confirmWin.destroy()
                            })
                            .catch(() => reject)
                    }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
                },
                onCancel: () => {
                }
            })
        },

        async handelApproval() {
            if (!this.opinions) {
                return this.$noticeWarning('反馈意见不能为空')
            }
            if (!this.form.fileInfoVO.length) {
                return this.$noticeWarning('附件不能为空')
            }

            let submitForm = this.$clone(this.currentCommit)
            submitForm.fileInfoVO = this.form.fileInfoVO.length ? this.form.fileInfoVO[0] : null
            submitForm.suggestion = this.opinions
            this.loading = true
            let res = await riskListApi.editByComments(submitForm)
            if (res.code === this.SUCCESS_CODE) {
                await this.submit(false)
            } else {
                this.$noticeWarning('保存反馈意见失败')
            }
            this.loading = false

        }
    }
}
</script>

<style lang="less" scoped>
.wrapper {
    padding: 20px;

    .title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 20px;
    }

    /deep/ .approval-item .ant-form-item-control-wrapper {
        width: 100%;
    }
}

.wrapper-row {
    padding-left: 55px;
    font-weight: bold;
    letter-spacing: 1px;
}

/deep/ .ant-form-item label {
    font-size: 12px;
}

/deep/ .ant-btn {
    border-radius: 5px;
}

/deep/ .ant-input {
    /*width: 70%;*/
    border-radius: 5px;
}

/deep/ .ant-card.ant-card-bordered {
    border-radius: 5px;
}

.ant-avatar-lg {
    width: 48px;
    height: 48px;
    line-height: 48px;
}

.list-content-item {
    color: rgba(0, 0, 0, 0.45);
    display: inline-block;
    vertical-align: middle;
    font-size: 14px;
    margin-left: 40px;

    span {
        line-height: 20px;
    }

    p {
        margin-top: 4px;
        margin-bottom: 0;
        line-height: 22px;
    }
}

.title-name {
    border-left: 5px solid #1890ff;
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 15px;
    height: 20px;
    line-height: 20px;
}

/deep/ .table-page-search-wrapper .ant-form-inline .ant-row .ant-col.ant-col-sm-24.ant-col-md-12 {
    padding-left: 80px;
}

/deep/ .ant-form-item .ant-form-item-control-wrapper {
    /*width: 100%;*/
}

/deep/ .col .ant-form-item .ant-form-item-control-wrapper {
    width: calc(100% - 135px);
}
</style>

